package com.example.xianji.fragment;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.activity.Main_BaiKeActivity;
import com.example.xianji.activity.Main_Choose_DaTing_LieBiaoActivity;
import com.example.xianji.activity.Main_Find_QiYeActivity;
import com.example.xianji.activity.Main_FuWuActivity;
import com.example.xianji.activity.Main_LoginActivity;
import com.example.xianji.activity.Main_QiYe_RuZhuActivity;
import com.example.xianji.activity.Main_Send_XuQiuActivity;
import com.example.xianji.activity.Main_Skill_Activity;
import com.example.xianji.activity.Main_ZhanHui_DaTingActivity;

import com.example.xianji.activity.Main_geren_send_fuwuActivity;
import com.example.xianji.activity.Main_newsActivity;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.HomeAdapter;
import com.example.xianji.adapter.NewsAdapter;
import com.example.xianji.adapter.EnterpriseAdapter;
import com.example.xianji.adapter.SkillAdapter;
import com.example.xianji.adapter.ViewPagerAdapter;
import com.example.xianji.BGARefresh.BGANormalRefreshViewHolder;
import com.example.xianji.BGARefresh.BGARefreshLayout;
import com.example.xianji.BGARefresh.BGARefreshLayout.BGARefreshLayoutDelegate;
import com.example.xianji.bean.FuWu;
import com.example.xianji.bean.Home;
import com.example.xianji.bean.ImageUrl;
import com.example.xianji.bean.Skill;
import com.example.xianji.bean.news;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.DownloadManagerUtils;
import com.example.xianji.utils.SaveSdk;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.MyListview;
import com.example.xianji.widgets.HomeFragmentViewPager;

import com.example.xianji.eventbus.DianJi_EventBus;
import com.example.xianji.receiver.DownloadApkReceiver;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.Manifest;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * 首页
 *
 * @author me
 */
public class HomeFragment extends Fragment implements
        OnPageChangeListener, OnClickListener, BGARefreshLayoutDelegate {
    private int mDisplayMetricsWidth;
    private int newWidth;
    private int padding;
    private HomeFragmentViewPager mHomeFragmentViewPager;
    private ViewPagerAdapter mViewPagerAdp;

    /** 从服务器端获取的广告图片信息 **/
    private ArrayList<ImageUrl> imageUrlList = new ArrayList<ImageUrl>();
    private ArrayList<ImageView> imageview_list = new ArrayList<ImageView>();
    private ImageView[] mDots;
    private LinearLayout llDots;
    private final long delay = 2 * 1000;
    private final int AUTO = 0;
    private RelativeLayout rlPublishRequire, rlPublishService, rlEnterpriseSettle,
            rlServicesLobby, rlTechChoose, rlRequireAnalysis, rlTechBBS,
            rlWiki, rlAppVersion,
            rlTechniqueResult, rlNewsInformation, rlNewsInformationBottom, rlHotRequire,
            rlHotEnterprise, rlTechniqueResultBottom,
            rlConsult, rlExhibitionLobby, rlRecentlyExhibition;
    private ImageView ivWiki;
    private BGARefreshLayout mBGARefreshLayout;
//    private SharedPreferences sp;
//    private Editor ed;
    private MyListview mlvHotRequire, mlvNewsInformation, mlvHotEnterprise,
            mlvTechniqueResult, mlvRecentlyExhibition;

    /** 版本号 **/
    private int version_code;
    private Button btnCancelAppVersion, btnSureAppVersion;
    private TextView tvAppVersion;
    /** 新闻资讯 **/
    private ArrayList<news> mNewsInformationList = new ArrayList<news>();
    /** 热门企业 **/
    private ArrayList<FuWu> mHotEnterprise = new ArrayList<FuWu>();
    /** 技术成果 **/
    private ArrayList<Skill> mTechniqueResult = new ArrayList<Skill>();
    /** 热门需求 **/
    private ArrayList<Home> mHotRequireList = new ArrayList<Home>();
    /** 最新展会 **/
    private ArrayList<Home> zhanhui_list = new ArrayList<Home>();
    /** 新闻列表适配器 **/
    private NewsAdapter mNewsAdapter;
    /** 企业列表适配器 **/
    private EnterpriseAdapter mEnterpriseAdapter;
    private HomeAdapter mHomeAdapter;
    /** 展会列表适配器 **/
    private HomeAdapter mZhanhuiAdapter;
    /** 技术列表适配器 **/
    private SkillAdapter mSkillAdapter;
    private DownloadApkReceiver downloadApkReceiver;
    // 是否安装过新版本包的判断：1表明已经下载过，0表明没有下载，安装后赋值0
    private int APK_EXIST = 1;
    // 没有统计时的url http://download.xianjichina.com/Android/xianji-latest.apk
    // 从服务器下载安装包的链接
    public static String URL = "http://download.xianjichina.com/Android/?c=xianji ";
    // 写到sdk的权限
    private int Request_Permission_WRITE_EXTERNAL = 1;
    public static boolean isLoadingAPk = false;
    private View view;
    //Fragment防止Activity获取为空指针
    private Context mContext = null;
    /*
     * BroadcastReceiver安全问题
     * BroadcastReceiver设计的初衷是从全局考虑可以方便应用程序和系统、应用程序之间、
     * 应用程序内的通信，所以对单个应用程序而言BroadcastReceiver是存在安全性问题的
     * (恶意程序脚本不断的去发送你所接收的广播)。
     * 为了解决这个问题LocalBroadcastManager就应运而生了。
     */
    private LocalBroadcastManager localBroadcastManager;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (imageview_list.size() == 0) {
                    initDots();
                    initViewPager();
                }
                mBGARefreshLayout.endRefreshing();
                llDots.setVisibility(View.VISIBLE);
                mlvHotRequire.setAdapter(mHomeAdapter);
                mlvNewsInformation.setAdapter(mNewsAdapter);
                mlvHotEnterprise.setAdapter(mEnterpriseAdapter);
                mlvTechniqueResult.setAdapter(mSkillAdapter);
                mlvRecentlyExhibition.setAdapter(mZhanhuiAdapter);
                XJApplication.cachThreadPool.execute(new Runnable() {

                    @Override
                    public void run() {
                        get_version();
                    }
                });
            }
            if (msg.what == 2) {
                mBGARefreshLayout.endLoadingMore();
                llDots.setVisibility(View.VISIBLE);
                mlvHotRequire.setAdapter(mHomeAdapter);
                mlvNewsInformation.setAdapter(mNewsAdapter);
                mlvHotEnterprise.setAdapter(mEnterpriseAdapter);
                mlvTechniqueResult.setAdapter(mSkillAdapter);
                mlvRecentlyExhibition.setAdapter(mZhanhuiAdapter);
            }
            if (msg.what == 4) {
                get_shengji_company3();
            }
        }
    };

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        init();
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_home();
            }
        });
        ViewClick();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /****************** 版本升级的点击事件 ***************************/
        BanbenClick();
        // 如果系统允许用DownLoadManger就注册
        if (canDownloadState(mContext)) {
            registerReceiver();
        }
    }

    private void ViewClick() {
        rlPublishRequire.setOnClickListener(this);
        rlPublishService.setOnClickListener(this);
        rlEnterpriseSettle.setOnClickListener(this);
        rlTechniqueResult.setOnClickListener(this);
        ivWiki.setOnClickListener(this);

        mBGARefreshLayout.setDelegate(this);
        mBGARefreshLayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(getActivity(), true));
        rlServicesLobby.setOnClickListener(this);
        rlTechChoose.setOnClickListener(this);
        rlRequireAnalysis.setOnClickListener(this);
        rlNewsInformation.setOnClickListener(this);
        rlTechBBS.setOnClickListener(this);
        rlWiki.setOnClickListener(this);
        rlNewsInformationBottom.setOnClickListener(this);
        rlHotRequire.setOnClickListener(this);
        rlHotEnterprise.setOnClickListener(this);
        rlTechniqueResultBottom.setOnClickListener(this);
        rlExhibitionLobby.setOnClickListener(this);
        rlRecentlyExhibition.setOnClickListener(this);
        rlConsult.setOnClickListener(this);
    }

    /****************** 版本升级的点击事件 ***************************/
    private void BanbenClick() {
        rlAppVersion.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        btnCancelAppVersion.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                rlAppVersion.setVisibility(View.GONE);
            }
        });

        btnSureAppVersion.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("market://details?id="
                        + "com.example.xianji");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                PackageManager pm = getActivity().getPackageManager();
                // 获取到包含项目报名的所有应用
                List<ResolveInfo> ResolveInfo_list = pm.queryIntentActivities(intent, 0);

                /* try { */

                if (ResolveInfo_list.size() > 0) {
                    String marketName = ResolveInfo_list.get(0).activityInfo.packageName;
                    /*
                     * Toast.makeText( getActivity(),
                     * ResolveInfo_list.get(0).activityInfo.packageName + "",
                     * 1).show();
                     */
                    // 获取所有应用的第一个应用去跳转
                    if (marketName.equals("com.oppo.market")// oppo
                            || marketName.equals("com.lenovo.leos.appstore")// 联想
                            || marketName.equals("com.lenovo.leos.appstore")
                            || marketName.equals("com.hiapk.marketpho")// 安智
                            || marketName.equals("com.huawei.appmarket")
                            || marketName.equals("com.meizu.mstore")) {
                        intent.setPackage(marketName);
                        getActivity().startActivity(intent);
                    } else {
                        // 不去应用市场，去服务器下载apk
                        DontGoMarket();
                    }
                } else {
                    // 不去应用市场,去服务器下载APK
                    DontGoMarket();
                }


                rlAppVersion.setVisibility(View.GONE);
            }
        });
    }

    private void init() {
        mDisplayMetricsWidth = getResources().getDisplayMetrics().widthPixels;
        rlPublishRequire = (RelativeLayout) view.findViewById(R.id.rl_publish_require_fragment_home);
        rlPublishService = (RelativeLayout) view.findViewById(R.id.rl_publish_service_fragment_home);
        rlEnterpriseSettle = (RelativeLayout) view.findViewById(R.id.rl_enterprise_settle_fragment_home);
        rlTechBBS = (RelativeLayout) view.findViewById(R.id.rl_tech_bbs_fragment_home);
        rlTechniqueResult = (RelativeLayout) view.findViewById(R.id.rl_technique_result_fragment_home);
        ivWiki = (ImageView) view.findViewById(R.id.iv_wiki_fragment_home);
        mBGARefreshLayout = (BGARefreshLayout) view.findViewById(R.id.bgarl_home_fragment);
        rlNewsInformation = (RelativeLayout) view.findViewById(R.id.rl_news_information_fragment_home);
        rlNewsInformationBottom = (RelativeLayout) view.findViewById(R.id.rl_news_information_bottom_fragment_home);
        rlHotRequire = (RelativeLayout) view.findViewById(R.id.rl_hot_require_fragment_home);
        rlHotEnterprise = (RelativeLayout) view.findViewById(R.id.rl_hot_enterprise_fragment_home);
        rlTechniqueResultBottom = (RelativeLayout) view.findViewById(R.id.rl_technique_result_bottom_fragment_home);
        rlConsult = (RelativeLayout) view.findViewById(R.id.rl_consult_fragment_home);
        rlExhibitionLobby = (RelativeLayout) view.findViewById(R.id.rl_exhibition_lobby_fragment_home);
        rlRecentlyExhibition = (RelativeLayout) view.findViewById(R.id.rl_recently_exhibition_fragment_home);
        mlvNewsInformation = (MyListview) view.findViewById(R.id.mlv_news_information_fragment_home);
        mlvHotRequire = (MyListview) view.findViewById(R.id.mlv_hot_require_fragment_home);
        mlvHotEnterprise = (MyListview) view.findViewById(R.id.mlv_hot_enterprise_fragment_home);
        mlvTechniqueResult = (MyListview) view.findViewById(R.id.mlv_technique_result_fragment_home);
        mlvRecentlyExhibition = (MyListview) view.findViewById(R.id.mlv_recently_exhibition_fragment_home);

        mHomeAdapter = new HomeAdapter(mContext, mHotRequireList,Contant.HomePage_Xuqiu_list);
        mNewsAdapter = new NewsAdapter(mContext, mNewsInformationList);
        mEnterpriseAdapter = new EnterpriseAdapter(mHotEnterprise, mContext);
        mSkillAdapter = new SkillAdapter(mContext, mTechniqueResult);
        mZhanhuiAdapter = new HomeAdapter(mContext, zhanhui_list,Contant.HomePage_Zhanhui_list);
        rlWiki = (RelativeLayout) view.findViewById(R.id.rl_wiki_fragment_home);
        rlAppVersion = (RelativeLayout) view.findViewById(R.id.rl_app_version_fragment_home);
        btnCancelAppVersion = (Button) view.findViewById(R.id.btn_cancel_app_version_fragment_home);
        btnSureAppVersion = (Button) view.findViewById(R.id.btn_sure_app_version_fragment_home);
        tvAppVersion = (TextView) view.findViewById(R.id.tv_app_version_fragment_home);
        try {
            version_code = mContext.getPackageManager().getPackageInfo(
                    "com.example.xianji", 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
//        sp = mContext.getSharedPreferences("text", mContext.MODE_PRIVATE);
//        ed = sp.edit();
        rlTechChoose = (RelativeLayout) view.findViewById(R.id.rl_tech_choose_fragment_home);
        rlServicesLobby = (RelativeLayout) view.findViewById(R.id.rl_services_lobby_fragment_home);
        rlRequireAnalysis = (RelativeLayout) view.findViewById(R.id.rl_require_analysis_fragment_home);
        mHomeFragmentViewPager = (HomeFragmentViewPager) view.findViewById(R.id.hfvp_fragment_home);
        newWidth = (int) (divideWidth(mDisplayMetricsWidth, 1080, 6) * 17);
        padding = (int) (divideWidth(mDisplayMetricsWidth, 1080, 6) * 9);
        mHomeFragmentViewPager.setFocusable(true);
        mHomeFragmentViewPager.setFocusableInTouchMode(true);
        llDots = (LinearLayout) view.findViewById(R.id.ll_dots_fragment_home);
        mHomeFragmentViewPager.setOnPageChangeListener(this);
        Main_newsActivity.high_light_word = new JSONArray();
    }

    /****************** 注册下载APK的广播 ****************************/
    private void registerReceiver() {
        localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        downloadApkReceiver = new DownloadApkReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        intentFilter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        localBroadcastManager.registerReceiver(downloadApkReceiver, intentFilter);
    }

    /**
     * 不去应用市场，直接去服务器下载
     */
    public void DontGoMarket() {
        if (canDownloadState(getActivity())) {
            String[] permission_Picture = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE};
            if (permissionCheck(permission_Picture)) {
                // 下载安装包
                downloadApk();
            } else {
                // 但是在Fragment中我们不能通过ActivityCompat.requestPermissions去请求，因为这样纸请求Fragment不能收到onRequestPermissionsResult。所以我们应该直接用XXXfragment.this.requestPermissions去请求权限。
                HomeFragment.this.requestPermissions(permission_Picture,
                        Request_Permission_WRITE_EXTERNAL);
            }
        } else {
            Intent intent1 = new Intent();
            intent1.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(URL);
            intent1.setData(content_url);
            getActivity().startActivity(intent1);
        }
    }

    /**
     * 初始化圆点
     */
    private void initDots() {
        if (imageUrlList.size() > 0) {
            mDots = new ImageView[imageUrlList.size()];
            llDots.removeAllViews();
            for (int i = 0; i < imageUrlList.size(); i++) {
                ImageView iv = new ImageView(mContext);
                LayoutParams lp = new LayoutParams(newWidth, newWidth);
                lp.leftMargin = padding;
                lp.rightMargin = padding;
                lp.topMargin = padding;
                lp.bottomMargin = padding;
                iv.setLayoutParams(lp);
                iv.setImageResource(R.drawable.dot_normal);
                llDots.addView(iv);
                mDots[i] = iv;
            }
            mDots[0].setImageResource(R.drawable.dot_selected);
        }
    }

    /**
     * 初始化viewpager图片
     */
    private void initViewPager() {
        for (int i = 0; i < imageUrlList.size(); i++) {
            ImageView iv = new ImageView(mContext);
            /**
             * 等比例宽高
             */
            iv.setAdjustViewBounds(true);
            iv.setScaleType(ScaleType.FIT_XY);
            ImageLoader.getInstance().displayImage(
                    Contant.lunbo + imageUrlList.get(i).getImageName(), iv);
            imageview_list.add(iv);
            final int a = i;

            iv.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    //跳转到浏览器
                    try {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        // intent.putExtra("fa", 1);
                        Uri content_url = Uri.parse(imageUrlList.get(a).getUrl());
                        intent.setClassName("com.android.browser","com.android.browser.BrowserActivity");
                        intent.setData(content_url);
                        startActivity(intent);
                    } catch (Exception e) {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri content_url = Uri.parse(imageUrlList.get(a).getUrl());
                        intent.setData(content_url);
                        startActivity(intent);
                    }
                }
            });
        }
        mViewPagerAdp = new ViewPagerAdapter(imageview_list, mContext);
        mHomeFragmentViewPager.setAdapter(mViewPagerAdp);
        mHomeFragmentViewPager.setCurrentItem(0);
        mHandler.sendEmptyMessageDelayed(AUTO, delay);
    }

    private Handler mHandler = new Handler() {

        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case AUTO:
                    int index = mHomeFragmentViewPager.getCurrentItem();
                    if (mHomeFragmentViewPager.getCurrentItem() == imageUrlList.size() - 1) {
                        index = -1;
                    }
                    mHomeFragmentViewPager.setCurrentItem(index + 1);
                    mHandler.sendEmptyMessageDelayed(AUTO, delay);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int arg0) {
        setCurrentDot(arg0 % imageUrlList.size());
    }

    private void setCurrentDot(int currentPosition) {
        for (int i = 0; i < mDots.length; i++) {
            if (i == currentPosition) {
                mDots[i].setImageResource(R.drawable.dot_selected);
            } else {
                mDots[i].setImageResource(R.drawable.dot_normal);
            }
        }
    }

    public double divideWidth(int screenWidth, int picWidth, int retainValue) {
        BigDecimal screenBD = new BigDecimal(Double.toString(screenWidth));
        BigDecimal picBD = new BigDecimal(Double.toString(picWidth));
        return screenBD.divide(picBD, retainValue, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 获取版本更新
     */
    public void get_version() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("api_origin", "origin_android");
        parms.addBodyParameter("version", version_code + "");
        httpUtils.send(HttpMethod.POST, Contant.banben_new, parms,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        // Toast.makeText(getActivity(),"网络异常",1).show();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject object = new JSONObject(arg0.result);
                            handler.sendEmptyMessage(4);
                            if (object.getInt("status") == 0) {
                                // 有版本更新
                                rlAppVersion.setVisibility(View.VISIBLE);
                                int new_version_code = version_code + 1;
                                tvAppVersion.setText("当前版本:" + version_code
                                        + " ,发现新版本：" + new_version_code
                                        + " ,是否更新？" + "\n"
                                );
                            } else {
                                // 没有新版本
                                // 把论坛版本更新是否下载过改为0,有版本更新时下载完成在广播接收里设置为1，为1时直接安装，为0时先下载再安装
                                PreferenceEngine.getInstance().putInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_APK_EXIST,0);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rl_publish_require_fragment_home) {
            if(PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME,Constant.SP.KEY_XIANJI_DENGLU,false)){
                mContext.startActivity(new Intent(mContext,Main_Send_XuQiuActivity.class));
            } else {
                Intent intent = new Intent(getActivity(),Main_LoginActivity.class);
                intent.putExtra("origin_login", 55);
                startActivity(intent);
            }
        } else if (v.getId() == R.id.rl_publish_service_fragment_home) {
            if(PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME,Constant.SP.KEY_XIANJI_DENGLU,false)){
                if(PreferenceEngine.getInstance().getInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_STATUS,5)==1){
                    // 可以申请企业入驻
                    mContext.startActivity(new Intent(mContext,Main_QiYe_RuZhuActivity.class));
                } else if (PreferenceEngine.getInstance().getInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_STATUS,5)==0) {
                    Toast.makeText(getActivity(), "正在审核，请耐心等待", Toast.LENGTH_SHORT).show();
                } else if (PreferenceEngine.getInstance().getInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_STATUS,5)==2) {
                    // 审核失败，可以再次申请企业入驻
                    mContext.startActivity(new Intent(mContext,Main_QiYe_RuZhuActivity.class));
                } else if (PreferenceEngine.getInstance().getInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_STATUS,5)==3) {
                    mContext.startActivity(new Intent(mContext,Main_geren_send_fuwuActivity.class));
                }
            } else {
                Intent intent = new Intent(getActivity(),Main_LoginActivity.class);
                intent.putExtra("origin_login", 55);
                startActivity(intent);
            }

        } else if (v.getId() == R.id.rl_enterprise_settle_fragment_home) {
            if(PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME,Constant.SP.KEY_XIANJI_DENGLU,false)){
                if(PreferenceEngine.getInstance().getString(Constant.SP.NAME,Constant.SP.KEY_XIANJI_TYPE,"").equals("FC")||
                        PreferenceEngine.getInstance().getString(Constant.SP.NAME,Constant.SP.KEY_XIANJI_TYPE,"").equals("AC")){
                    mContext.startActivity(new Intent(mContext,
                            Main_geren_send_fuwuActivity.class));
                } else {
                    if(PreferenceEngine.getInstance().getInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_STATUS,5)==1) {
                        // 可以申请企业入驻
                        mContext.startActivity(new Intent(mContext,Main_QiYe_RuZhuActivity.class));
                        // mContext.startActivity(new
                        // Intent(mContext,Main_QiYe_RuZhuActivity.class));
                    }else if(PreferenceEngine.getInstance().getInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_STATUS,5)==0){
                        Toast.makeText(getActivity(), "正在审核，请耐心等待", Toast.LENGTH_SHORT).show();
                    }else if(PreferenceEngine.getInstance().getInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_STATUS,5)==2){
                        // 审核失败，可以再次申请企业入驻
                        mContext.startActivity(new Intent(mContext,Main_QiYe_RuZhuActivity.class));
                    }else if(PreferenceEngine.getInstance().getInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_STATUS,5)==3){
                        mContext.startActivity(new Intent(mContext,Main_geren_send_fuwuActivity.class));
                    }
                }
            } else {
                mContext.startActivity(new Intent(mContext,Main_QiYe_RuZhuActivity.class));
            }
        } else if (v.getId() == R.id.rl_technique_result_fragment_home) {
            mContext.startActivity(new Intent(mContext,Main_Skill_Activity.class));
        } else if (v.getId() == R.id.iv_wiki_fragment_home) {
            // 百科入口
            startActivity(new Intent(getActivity(), Main_BaiKeActivity.class));
        } else if (v.getId() == R.id.rl_services_lobby_fragment_home) {
            mContext.startActivity(new Intent(getActivity(),Main_FuWuActivity.class));
        } else if (v.getId() == R.id.rl_tech_choose_fragment_home) {
            // 选型大厅
            Contant.choose_dating_back = 2;
            mContext.startActivity(new Intent(getActivity(),Main_Choose_DaTing_LieBiaoActivity.class));
        } else if (v.getId() == R.id.rl_require_analysis_fragment_home) {
            EventBus.getDefault().postSticky(new DianJi_EventBus(false, true));
        } else if (v.getId() == R.id.rl_news_information_fragment_home) {
            mContext.startActivity(new Intent(getActivity(),Main_newsActivity.class));
            // 在这里默认异常抛出情况，人为抛出一个运行时异常
            // throw new RuntimeException("自定义异常：这是自己抛出的异常");
        } else if (v.getId() == R.id.rl_tech_bbs_fragment_home) {
            //跳转到浏览器
            try {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                // intent.putExtra("fa", 1);
                Uri content_url = Uri.parse("http://m.bbs.xianjichina.com/");

                // 如果手机本身没有默认浏览器，就跳转到系统自带的浏览器，避免三星机型崩溃问题
                intent.setClassName("com.android.browser","com.android.browser.BrowserActivity");
                intent.setData(content_url);
                startActivity(intent);
            } catch (Exception e) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                // intent.putExtra("fa", 1);
                Uri content_url = Uri.parse("http://m.bbs.xianjichina.com/");
                intent.setData(content_url);
                startActivity(intent);
            }
        } else if (v.getId() == R.id.rl_wiki_fragment_home) {
            // 百科入口
            startActivity(new Intent(getActivity(), Main_BaiKeActivity.class));
            // Toast.makeText(getActivity(),"此功能暂时还没有开通!", 0).show();
        } else if (v.getId() == R.id.rl_news_information_bottom_fragment_home) {
            startActivity(new Intent(getActivity(), Main_newsActivity.class));
        } else if (v.getId() == R.id.rl_hot_require_fragment_home) {
            EventBus.getDefault().postSticky(new DianJi_EventBus(false, true));
        } else if (v.getId() == R.id.rl_hot_enterprise_fragment_home) {
            startActivity(new Intent(getActivity(),Main_Find_QiYeActivity.class));
        } else if (v.getId() == R.id.rl_technique_result_bottom_fragment_home) {
            startActivity(new Intent(getActivity(), Main_Skill_Activity.class));
        }else if (v.getId() == R.id.rl_exhibition_lobby_fragment_home) {
            startActivity(new Intent(getActivity(),Main_ZhanHui_DaTingActivity.class));
        } else if (v.getId() == R.id.rl_recently_exhibition_fragment_home) {
            startActivity(new Intent(getActivity(),Main_ZhanHui_DaTingActivity.class));
        } else if (v.getId() == R.id.rl_consult_fragment_home) {
            try {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                // intent.putExtra("fa", 1);
                Uri content_url = Uri.parse("http://m.xianjichina.com/doing_appdownqybd");
                // 如果手机本身没有默认浏览器，就跳转到系统自带的浏览器，避免三星机型崩溃问题
                intent.setClassName("com.android.browser","com.android.browser.BrowserActivity");
                intent.setData(content_url);
                startActivity(intent);
            } catch (Exception e) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse("http://m.xianjichina.com/doing_appdownqybd");
                intent.setData(content_url);
                startActivity(intent);
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mHomeFragmentViewPager != null) {
            mHomeFragmentViewPager.setFocusable(true);
            mHomeFragmentViewPager.setFocusableInTouchMode(true);
        }
        if (Contant.login_resume == 1) {
            // 如果登录成功，加载一下企业升级的状态
            get_shengji_company3();
            // Contant.login_resume=0;
        }
    }

    public void get_home() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME,Constant.SP.KEY_XIANJI_TOKEN,""));
//        parms.addBodyParameter("token", sp.getString("xianji_token", ""));
        parms.addBodyParameter("page", 1 + "");
        parms.addBodyParameter("api_origin", "origin_android");
        parms.addBodyParameter("version", version_code + "");

        httpUtils.send(HttpMethod.POST, Contant.home, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        mBGARefreshLayout.endRefreshing();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        PreferenceEngine.getInstance().putString(Constant.SP.NAME,Constant.SP.KEY_RESULT,arg0.result);
                        parse(arg0.result);
                    }
                });
    }

    /**
     * 判断是否升级为企业用户
     */
    public void get_shengji_company3() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME,Constant.SP.KEY_XIANJI_TOKEN,""));
//        parms.addBodyParameter("token", sp.getString("xianji_token", ""));

        httpUtils.send(HttpMethod.POST, Contant.is_shengji_compny, parms,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        try {
                            JSONObject obj = new JSONObject(arg0.result);
                            if (obj.getInt("status") == 3) {
                                // 如果返回3表明升级企业通过
                                if(PreferenceEngine.getInstance().getString(Constant.SP.NAME,Constant.SP.KEY_XIANJI_TYPE,"").equals("FP")||
                                        PreferenceEngine.getInstance().getString(Constant.SP.NAME,Constant.SP.KEY_XIANJI_TYPE,"").equals("AP")){
                                    // 记录的还是个人 账号
                                    PreferenceEngine.getInstance().putBoolean(Constant.SP.NAME,Constant.SP.KEY_XIANJI_DENGLU,false);
                                }
                            }
                            // 判断 个人升级为企业的标记
                            PreferenceEngine.getInstance().putInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_STATUS,obj.getInt("status"));
//                            ed.putInt("xianji_status", obj.getInt("status"));
//                            ed.commit();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    public void parse(String result) {
        try {
            JSONObject object = new JSONObject(result);
            if (object.getInt("status") == 1) {
                mHotRequireList.clear();
                imageUrlList.clear();
                mNewsInformationList.clear();
                mHotEnterprise.clear();
                mTechniqueResult.clear();
                zhanhui_list.clear();
                JSONArray array = object.getJSONArray("data");
                JSONArray array0 = array.getJSONArray(0);

                for (int i = 0; i < array0.length(); i++) {
                    JSONObject object0 = array0.getJSONObject(i);
                    ImageUrl imageUrl = new ImageUrl();
                    imageUrl.setImageName(object0.getString("image"));
                    imageUrl.setUrl(object0.getString("url"));
                    imageUrlList.add(imageUrl);
                }
                handler.sendEmptyMessage(1);

                JSONArray array1 = array.getJSONArray(1);// 热门需求
                JSONArray array2 = array.getJSONArray(2);// 新闻资讯
                JSONArray array3 = array.getJSONArray(3);// 热门企业
                JSONArray array4 = array.getJSONArray(4);// 技术成果
                JSONArray array5 = array.getJSONArray(5);// 最新展会

                // 热门需求
                for (int i = 0; i < array1.length(); i++) {
                    JSONObject obj = array1.getJSONObject(i);
                    Home mHome = new Home();
                    mHome.setCity_name(obj.getString("city_name"));
                    mHome.setProvince_name(obj.getString("province_name"));
                    mHome.setTitle(obj.getString("title"));
                    mHome.setId(obj.getString("id"));
                    mHotRequireList.add(mHome);
                }
                //新闻资讯
                for (int i = 0; i < array2.length(); i++) {
                    JSONObject obj2 = array2.getJSONObject(i);
                    news mnews = new news();
                    mnews.setDescription(obj2.getString("description"));
                    mnews.setId(obj2.getString("id"));
                    mnews.setPath(obj2.getJSONObject("uploads").getString(
                            "path"));
                    mnews.setName(obj2.getJSONObject("uploads").getString(
                            "name"));
                    mnews.setNews_title(obj2.getString("news_title"));
                    JSONArray hight_array = new JSONArray();
                    mnews.setHight_light_pos(hight_array);
                    mnews.setDetail_hig_light(hight_array);
                    mNewsInformationList.add(mnews);
                }
                // 热门企业
                for (int i = 0; i < array3.length(); i++) {
                    JSONObject obj3 = array3.getJSONObject(i);
                    FuWu mFuWu = new FuWu();
                    mFuWu.setTitle(obj3.getString("title"));
                    mFuWu.setId(obj3.getInt("id"));
                    mFuWu.setProvince_name(obj3.getString("province_name"));
                    mFuWu.setCity_name(obj3.getString("city_name"));
                    mFuWu.setCat_name(obj3.getString("tag_name"));
                    mHotEnterprise.add(mFuWu);

                }
                // 技术成果列表
                for (int i = 0; i < array4.length(); i++) {
                    JSONObject obj4 = array4.getJSONObject(i);
                    Skill mSkill = new Skill();
                    mSkill.setTitle(obj4.getString("title"));
                    mSkill.setName(obj4.getJSONObject("parents").getString(
                            "name"));
                    mSkill.setId(obj4.getString("id"));
                    mTechniqueResult.add(mSkill);
                }
                // 最新展会
                for (int i = 0; i < array5.length(); i++) {
                    JSONObject obj5 = array5.getJSONObject(i);
                    Home mHome = new Home();
                    mHome.setTime(obj5.getString("zdate"));
                    mHome.setTitle(obj5.getString("ztitle"));
                    mHome.setId(obj5.getString("id"));
                    zhanhui_list.add(mHome);
                }
                handler.sendEmptyMessage(2);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NewsAdapter.AnimateFirstDisplayListener.displayedImages.clear();
        handler.removeCallbacksAndMessages(null);

        if (downloadApkReceiver != null) {
            //取消注册广播,防止内存泄漏
            localBroadcastManager.unregisterReceiver(downloadApkReceiver);
        }
        mContext = null;
    }

    // 如果info.activityInfo.packageName为android,则没有设置,否则,有默认的程序.

    /***************** 是否适合用DownloadManager ************************************/
    private static boolean canDownloadState(Context ctx) {
        try {
            int state = ctx.getPackageManager().getApplicationEnabledSetting(
                    "com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void downloadApk() {
        int existState = PreferenceEngine.getInstance().getInt(Constant.SP.NAME,Constant.SP.KEY_XIANJI_APK_EXIST,0);
//        int existState = sp.getInt("Xianji_APK_EXIST", 0);

        if (existState == APK_EXIST) {
            // 直接安装APK
            DownloadManagerUtils.installApk(mContext.getApplicationContext());
        } else {
            // public long enqueue(Request request) 执行下载，返回
            // downloadId，downloadId 可用于后面查询下载信息。
            // 若网络不满足条件、Sdcard 挂载中、超过最大并发数等异常则会等待下载，正常则直接下载。
            // Toast.makeText(getActivity(), "更新包下载中...", 0).show();
            /*************** 已经在下载时不能再下载 *******************************/
            if (!isLoadingAPk) {
                if (new File(DownloadManagerUtils.APP_FILE_NAME).exists()) {
                    // 如果文件名已经存在，删掉再下载
                    SaveSdk.deleteFile_baike(getActivity(),
                            DownloadManagerUtils.APP_FILE_NAME);
                }
                final long id = DownloadManagerUtils.downloadApk(mContext.getApplicationContext(),
                        URL, "APK更新", "更新包下载中...");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        queryDownloadManager(id, getActivity());
                    }
                }, 1000);
                isLoadingAPk = true;
            } else {
                Toast.makeText(getActivity(), "正在下载中....", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    /**
     * @param id 下载工具并没有提供相应的回调接口用于返回实时的下载进度状态。 可以通过 DownloadManager.query
     *           方法进行查询， 该方法返回一个 Cursor 对象，具体看以下代码：
     */
    public static void queryDownloadManager(long id, Context context) {
        DownloadManager mDownloadManager = (DownloadManager) context
                .getSystemService(Context.DOWNLOAD_SERVICE);
        // Cursor query(Query query) 查询下载信息。
        DownloadManager.Query query = new DownloadManager.Query()
                .setFilterById(id);
        Cursor cursor = mDownloadManager.query(query);

        if (cursor != null) {

            while (cursor.moveToNext()) {

                String bytesDownload = cursor
                        .getString(cursor
                                .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                String description = cursor.getString(cursor
                        .getColumnIndex(DownloadManager.COLUMN_DESCRIPTION));
                String cid = cursor.getString(cursor
                        .getColumnIndex(DownloadManager.COLUMN_ID));
                String localUri = cursor.getString(cursor
                        .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                String mimeType = cursor.getString(cursor
                        .getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
                String title = cursor.getString(cursor
                        .getColumnIndex(DownloadManager.COLUMN_TITLE));
                String status = cursor.getString(cursor
                        .getColumnIndex(DownloadManager.COLUMN_STATUS));
                String totalSize = cursor
                        .getString(cursor
                                .getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            }
            cursor.close();
        }
    }

    /**
     * Android 6.0以上的申请权限
     *
     * @param permissionManifest
     * @return
     */
    private boolean permissionCheck(String[] permissionManifest) {
        if (Build.VERSION.SDK_INT >= 23) {
            boolean permissionState = true;
            for (String permission : permissionManifest) {
                if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                    permissionState = false;
                }
            }
            if (!permissionState) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
        if (requestCode == Request_Permission_WRITE_EXTERNAL) {
            // 拍照
            if (grantResults.length > 0) {
                boolean take_photo_flag = false;
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        take_photo_flag = true;
                    }
                }
                if (take_photo_flag) {
                    // 申请成功，可以拍照
                    downloadApk();
                } else {
                    Toast.makeText(getActivity(), "请先开通权限哦", Toast.LENGTH_SHORT).show();
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        XJApplication.cachThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                get_home();
            }
        });
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }
}
